﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.Xml;

namespace QA.TFS.Rules.Validation
{

  [DisplayName("Validate TagContent")]
  [Description("Validates whether tag in question contains the intended value")]
  public class CustomValidateTag : ValidationRule
  {

    [Description("TagName value")]
    private string TagNameValue;
    public string TagName
    {
      get { return TagNameValue; }
      set { TagNameValue = value; }
    }

    [Description("TagName Content Value")]
    private string IntendedTagValue;
    public string IntendedValue
    {
      get { return IntendedTagValue; }
      set { IntendedTagValue = value; }
    }

    [DisplayName("Validate TagContent")]
    [Description("Validates whether tag in question contains the intended value")]
    public override void Validate(object sender, ValidationEventArgs e)
    {

      e.IsValid = false;

      XmlNodeList nodes = e.Response.XmlDocument.GetElementsByTagName(TagName);

      if (nodes.Count > 0)
      {

        e.IsValid = true;
        foreach (XmlNode node in nodes)
        {
          if (!string.Equals(node.InnerText, IntendedValue, StringComparison.InvariantCultureIgnoreCase))
          {
            e.IsValid = false;
            break;
          }
        }

      }

      // If the validation fails, set the error text that the user sees
      if (!e.IsValid)
      {
        e.Message = String.Format("{0} Tag does not contain {1}", TagName, IntendedValue);
      }

    }

  }

}
